package engine.systems.ui.book
{
	import engine.classes.enumerations.SystemPriority;
	import engine.groups.Group;
	import engine.systems.spatial.spatialOffset.SpatialOffsetData;
	import engine.systems.update.GameSystem;
	
	
	public class BookSystem extends GameSystem
	{
		private const BOOK:String = "book";
		
		private var deltaX:Number;
		private var deltaY:Number;
		private var data:SpatialOffsetData;
		
		public function BookSystem()
		{
			super(BookNode, updateNode, nodeAdded, nodeRemoved);
			
			this.priority = SystemPriority.PRE_MOTION;
		}
		
		private function updateNode(node:BookNode, time:Number):void
		{
			if(!node.book.invalidate) return;
			
			data = node.offset.get(BOOK);
			
			if(node.book.ease)
			{
				if(node.book.handler != null) node.book.handler(node, time);
				else
				{
					deltaX = node.book.offsetX - data.x;
					deltaY = node.book.offsetY - data.y;
					
					/**
					 * Hardcoded 0.1 threshold. This could be a Book variable, but 0.1 seems to work for anything
					 * with a decent easing rate.
					 */
					if(Math.abs(deltaX) < 0.1 && Math.abs(deltaY) < 0.1)
					{
						node.book.invalidate = false;
						return;
					}
					
					data.x += deltaX * node.book.rate * time;
					data.y += deltaY * node.book.rate * time;
				}
			}
			else
			{
				data.x = node.book.offsetX;
				data.y = node.book.offsetY;
				
				node.book.invalidate = false;
			}
		}
		
		private function nodeAdded(node:BookNode):void
		{
			node.offset.add(BOOK, new SpatialOffsetData(node.book.offsetX, node.book.offsetY));
		}
		
		private function nodeRemoved(node:BookNode):void
		{
			node.offset.remove(BOOK);
		}
	}
}